package com.socialsoftware.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.socialsoftware.R;

import java.util.List;

public class ImageGridAdapter extends RecyclerView.Adapter<ImageGridAdapter.ImageViewHolder> {

    private Context context;
    private List<String> imageUrls;

    public ImageGridAdapter(Context context, List<String> imageUrls) {
        this.context = context;
        this.imageUrls = imageUrls;
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_grid_image, parent, false);
        
        // Calculate the height based on the width to maintain a square aspect ratio
        int width = parent.getMeasuredWidth() / determineSpanCount(imageUrls.size());
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.height = width;
        view.setLayoutParams(layoutParams);
        
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        String imageUrl = imageUrls.get(position);
        
        Glide.with(context)
                .load(imageUrl)
                .centerCrop()
                .into(holder.imageView);
                
        holder.imageView.setOnClickListener(v -> {
            // Handle image click (e.g., open full-screen viewer)
        });
    }

    @Override
    public int getItemCount() {
        return imageUrls.size();
    }
    
    private int determineSpanCount(int imageCount) {
        if (imageCount == 1) return 1;
        else if (imageCount <= 4) return 2;
        else return 3;
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;

        ImageViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.iv_image);
        }
    }
} 